package com.memoryangelapplication;

/*
 * User Login Validation And Device Registration Process Activate Background Service Running Handlers*/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;
import com.memoryangelapplication.constant.MemoryAngelConstant;
import com.memoryangelapplication.notification.MemoryAngel_Subscription;
import com.memoryangelapplication.services.EventAlarm;
import com.memoryangelapplication.services.NetworkUtility;
import com.memoryangelapplication.services.PendingEventAlarm;

import java.io.UnsupportedEncodingException;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.KeyguardManager.KeyguardLock;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

public class MemoryAngelLoading extends Activity {
	private static final String DATABASE_NAME = "memoryangel.db";
	private static final String TAG = null;
	// Master Tables
	private String MEM_USER = "table_user";
	private String MEM_EVENT = "table_events";
	 Date currenTimeZone;
	MemoryAngelDBLoader db;
	ProgressDialog mProgressDialog;
	ArrayList<String> memLoginArray = new ArrayList<String>();
	EditText etUserName, etPassWord;
	InputStream is = null;
	StringBuilder sb = null;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	String result;
	String mainUrl = null;
	JSONArray jArray;
	int loginState = 0;
	int AccountAcive = 0;
	String currentOPID;
	String formatso3;
	long timestamp = 0;
    String userEmail,userPass;
	ArrayList<String> eventslist = new ArrayList<String>();
	 String ddd;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Remove title bar
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    //Remove notification bar
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.memory_angel_loading);
		//APK-6
	    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
	    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		//APK 5
	    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		getWindow().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		//getWindow().addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		//APK-4
		KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);  
		KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); 
		lock.disableKeyguard();
		
        Log.e("ERROR :", "currenTimeZone " + "" + ddd);
		
		etUserName = (EditText) findViewById(R.id.email_id);
		etPassWord = (EditText) findViewById(R.id.password);

		db = new MemoryAngelDBLoader(this);
		db.getWritableDatabase();
		db.close();
		
		Date date=new Date();
		
		
		int gmtOffset = TimeZone.getDefault().getRawOffset();
		long nowunixtime = (System.currentTimeMillis() + gmtOffset) / 1000;
		
		
		Long tsLong = System.currentTimeMillis()/1000;
		String ts = tsLong.toString();
		Log.d("ERROR :", "DJJJJJ: " + nowunixtime + "/" + ts);
	    Log.e("ERROR :", "VVVVVV DATE 1: " + "" + nowunixtime);
	    
	           
		// Start service using AlarmManager
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.SECOND, 10);

		Intent intent = new Intent(this, BackgroundService.class);
		PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
		AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		// for 30 mint 60*60*1000
		alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
				60 * 1 * 1000, pintent);
		startService(new Intent(getBaseContext(), BackgroundService.class));

        if(CHKsynchstate() ==1){
        	listEvents();
        }

		Button userLogin = (Button) findViewById(R.id.enter_button);
		userLogin.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// sendingEvents();
				// getEvents();
				
				///////////
				//Event Check Alarm - Created Only once
				Bundle bundle = new Bundle();
				PendingEventAlarm alarm1 = new PendingEventAlarm(getApplicationContext(), bundle, 1);
				///////////
				
				
				//////////

				if (!NetworkUtility.isNetWorking(MemoryAngelLoading.this)) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							MemoryAngelLoading.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("NETWOK ERROR");
					// Setting Dialog Message
					alertDialog
							.setMessage("Please Check Your Network Connection..");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}

				else {
					mainUrl = MemoryAngelConstant.MA_USER_LOGIN;

					if (etUserName.length() == 0 || etPassWord.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								MemoryAngelLoading.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("INVALID LOGIN");
						// Setting Dialog Message
						alertDialog
								.setMessage("Please Enter User Name And Password..");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;

					} else {
						validateUserLogin();
					}

				}
			}

		});
		
		Button userLoginFoget = (Button) findViewById(R.id.btnForgot);
		userLoginFoget.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent i = new Intent(
						android.content.Intent.ACTION_VIEW,
						Uri.parse("http://memoryangel.com/devmangel/en/carer/register"));
				startActivity(i);
			}
		});
		
	}


	private void listEvents() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(getBaseContext(),
				MemoryAngelEventsList.class);
		// Pass all data m_name_in_card
		intent.putExtra("mem_angel_opID", currentOPID);
		intent.putExtra("mem_state_ID", "REGISTERED");
		startActivityForResult(intent, 0);
		finish();
		return;
	}

	// Check synch state for departure the login user
	protected int CHKsynchstate() {
		SQLiteDatabase mydb = openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		Cursor Chktblsynch = null;

		try {
			Chktblsynch = mydb.query(MEM_USER, null, null, null, null, null,
					null);
		} catch (Exception e1) {
		}
		if (Chktblsynch != null) {
			if (Chktblsynch.getCount() > 0) {
				while (Chktblsynch.moveToNext()) {
					currentOPID = Chktblsynch.getString(5);
					userEmail = Chktblsynch.getString(2);
					userPass = Chktblsynch.getString(8);
					
					Log.e("ERROR :", "currentOPID :" + currentOPID);
				}
				Chktblsynch.close();
				mydb.close();
				return 1;
			} else {

				Chktblsynch.close();
				mydb.close();
				return 0;
			}
		} else {
			mydb.close();
			return 0;
		}
	}
	
	protected void validateUserLogin() {
		// TODO Auto-generated method stub
		new UploadingInvoiceDataValues().execute();
	}

	private class UploadingInvoiceDataValues extends
			AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(MemoryAngelLoading.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Login");
			// Set progressdialog message
			mProgressDialog.setMessage("Processing Login....");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		Handler alertHandler = new Handler() {

		};

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(mainUrl);
				JSONObject json = new JSONObject();
				if(AccountAcive == 202){
					json.put("record1", userEmail);
					json.put("record2", userPass);
				}
				else{
					String password = etPassWord.getText().toString();
					String encriptedPass = md5Java(password);

					json.put("record1", etUserName.getText().toString());
					json.put("record2", encriptedPass);
				}
				

				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "request :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						Log.e("REQUEST :", "Login Result :" + result);
						jArray = new JSONArray(result);
						JSONObject json_data = null;
						for (int i = 0; i < jArray.length(); i++) {
							json_data = jArray.getJSONObject(i);
							String login_state = json_data
									.getString("login_state");
							if (login_state.equals("success")) {
								loginState = 1;
							} else if (login_state.equals("false")) {
								loginState = 2;
							} else if (login_state.equals("expaired")){
								loginState = 3;
							}
						}
					}

				}

			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			if (loginState == 1) {
				Intent intentDirectLog = new Intent(getBaseContext(),
						MemoryAngelUserRegister.class);
				intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intentDirectLog.putExtra("TAGID", etUserName.getText()
						.toString());
				startActivity(intentDirectLog);
				finish();
				return;
			} else if (loginState == 2) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						MemoryAngelLoading.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("INVLID LOGIN");
				// Setting Dialog Message
				alertDialog
						.setMessage("Please Register On http://memoryangel.com/..");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}else if (loginState == 3){
				String emailUser =etUserName.getText().toString();
				Intent intentSubcription = new Intent(getBaseContext(), MemoryAngel_Subscription.class);
				intentSubcription.putExtra("TAGIDEMAIL", emailUser);
				startActivity(intentSubcription);
			}
			else {
				listEvents();
			}

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.memory_angel_loading, menu);
		return true;
	}

	public static String md5Java(String message) {
		String digest = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] hash = md.digest(message.getBytes("UTF-8"));
			// converting byte array to Hexadecimal String
			StringBuilder sb = new StringBuilder(2 * hash.length);
			for (byte b : hash) {
				sb.append(String.format("%02x", b & 0xff));
			}
			digest = sb.toString();
		} catch (UnsupportedEncodingException ex) {
			Logger.getLogger(MemoryAngelLoading.class.getName()).log(
					Level.SEVERE, null, ex);
		} catch (NoSuchAlgorithmException ex) {
			Logger.getLogger(MemoryAngelLoading.class.getName()).log(
					Level.SEVERE, null, ex);
		}
		return digest;
	}

	// ===============================================================================
	// DownloadJSON AsyncTask
	private class fetchingEvents extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(MemoryAngelLoading.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Loading Events...");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Get Events Results
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				// RegisterEventsUrl
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(
						"http://memoryangel.com/wakandroid/UpdateandGetevent.php");
				JSONObject json = new JSONObject();
				json.put("reqEvents", eventslist);
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				String jsonStr = json.toString();
				String formatso1 = jsonStr.toString().replace("\\", "");
				String formatso2 = formatso1.toString().replace("}]\"}", "}]}");
				String formatso3 = formatso2.toString().replace("\"[{", "[{");

				Log.e("REQUEST :", "JSON REQ :" + formatso3);
				httppost.setHeader("json", formatso2);
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

				if (is != null) {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					Log.v(TAG, "result XXX RESPONCE :" + result);
					JSONObject jsonResponse = new JSONObject(result);
					JSONArray jsonArray = jsonResponse
							.getJSONArray("eventlist");
				}
			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			// Locate the listview in listview_main.xml
			mProgressDialog.dismiss();
			eventslist.clear();

		}
	}
	
	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

}
